import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Tag,
  Space,
  Button,
  Input,
  Select,
  Row,
  Col,
  message,
  Modal,
  Form,
  Popconfirm,
  Avatar,
  Switch,
  Tooltip
} from 'antd';
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ReloadOutlined,
  KeyOutlined,
  UserOutlined
} from '@ant-design/icons';
import {
  getUserList,
  createUser,
  updateUser,
  deleteUser,
  batchDeleteUsers,
  resetUserPassword,
  updateUserStatus,
  type User,
  type UserListParams,
  type CreateUserData,
  type UpdateUserData
} from '../../api/user';
import dayjs from 'dayjs';

const { Option } = Select;

export default function Administrators() {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [searchParams, setSearchParams] = useState<UserListParams>({});
  
  // 模态框状态
  const [modalVisible, setModalVisible] = useState(false);
  const [modalType, setModalType] = useState<'create' | 'edit' | 'resetPassword'>('create');
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [form] = Form.useForm();

  // 获取用户列表
  const fetchUsers = async (params: UserListParams = {}) => {
    setLoading(true);
    try {
      const response = await getUserList({
        page: pagination.current,
        limit: pagination.pageSize,
        ...searchParams,
        ...params
      });
      
      if (response.data.code === 0) {
        setUsers(response.data.data.users);
        setPagination(prev => ({
          ...prev,
          total: response.data.data.pagination.total
        }));
      } else {
        message.error(response.data.message || '获取用户列表失败');
      }
    } catch (error) {
      message.error('网络错误，请稍后重试');
      console.error('获取用户列表错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 搜索处理
  const handleSearch = () => {
    setPagination(prev => ({ ...prev, current: 1 }));
    fetchUsers({ page: 1 });
  };

  // 重置搜索
  const handleReset = () => {
    setSearchParams({});
    setPagination(prev => ({ ...prev, current: 1 }));
    fetchUsers({ page: 1 });
  };

  // 打开创建用户模态框
  const handleCreate = () => {
    setModalType('create');
    setCurrentUser(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 打开编辑用户模态框
  const handleEdit = (record: User) => {
    setModalType('edit');
    setCurrentUser(record);
    form.setFieldsValue({
      username: record.username,
      email: record.email,
      tel: record.tel,
      isAdmin: record.isAdmin,
      status: record.status
    });
    setModalVisible(true);
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      if (modalType === 'create') {
        const response = await createUser(values as CreateUserData);
        if (response.data.code === 0) {
          message.success('创建用户成功');
          setModalVisible(false);
          fetchUsers();
        } else {
          message.error(response.data.message || '创建用户失败');
        }
      } else if (modalType === 'edit' && currentUser) {
        const response = await updateUser(currentUser._id, values as UpdateUserData);
        if (response.data.code === 0) {
          message.success('更新用户成功');
          setModalVisible(false);
          fetchUsers();
        } else {
          message.error(response.data.message || '更新用户失败');
        }
      }
    } catch (error) {
      message.error('操作失败，请稍后重试');
    }
  };

  // 删除用户
  const handleDelete = async (id: string) => {
    try {
      const response = await deleteUser(id);
      if (response.data.code === 0) {
        message.success('删除成功');
        fetchUsers();
      } else {
        message.error(response.data.message || '删除失败');
      }
    } catch (error) {
      message.error('网络错误，请稍后重试');
    }
  };

  // 页面初始化
  useEffect(() => {
    fetchUsers();
  }, [pagination.current, pagination.pageSize]);

  const columns = [
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      width: 80,
      render: (avatar: string) => (
        <Avatar src={avatar} icon={<UserOutlined />} />
      ),
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 120,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 180,
      render: (email: string) => email || '-',
    },
    {
      title: '手机号',
      dataIndex: 'tel',
      key: 'tel',
      width: 120,
      render: (tel: string) => tel || '-',
    },
    {
      title: '角色',
      dataIndex: 'isAdmin',
      key: 'isAdmin',
      width: 100,
      render: (isAdmin: boolean) => (
        <Tag color={isAdmin ? 'red' : 'blue'}>
          {isAdmin ? '管理员' : '普通用户'}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusMap = {
          '启用': { color: 'green', text: '启用' },
          '禁用': { color: 'orange', text: '禁用' },
          '封禁': { color: 'red', text: '封禁' }
        };
        const statusInfo = statusMap[status as keyof typeof statusMap] || { color: 'default', text: status };
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (record: User) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EditOutlined />}
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          {!record.isAdmin && (
            <Popconfirm
              title="确定要删除这个用户吗？"
              onConfirm={() => handleDelete(record._id)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="link"
                danger
                icon={<DeleteOutlined />}
                size="small"
              >
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <Card>
      {/* 搜索栏 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Input
            placeholder="搜索用户名、邮箱、手机号"
            prefix={<SearchOutlined />}
            value={searchParams.keyword}
            onChange={(e) => setSearchParams(prev => ({ ...prev, keyword: e.target.value }))}
            onPressEnter={handleSearch}
          />
        </Col>
        <Col span={4}>
          <Select
            placeholder="用户状态"
            style={{ width: '100%' }}
            allowClear
            value={searchParams.status}
            onChange={(value) => setSearchParams(prev => ({ ...prev, status: value }))}
          >
            <Option value="启用">启用</Option>
            <Option value="禁用">禁用</Option>
            <Option value="封禁">封禁</Option>
          </Select>
        </Col>
        <Col span={4}>
          <Select
            placeholder="用户角色"
            style={{ width: '100%' }}
            allowClear
            value={searchParams.isAdmin}
            onChange={(value) => setSearchParams(prev => ({ ...prev, isAdmin: value }))}
          >
            <Option value={true}>管理员</Option>
            <Option value={false}>普通用户</Option>
          </Select>
        </Col>
        <Col span={6}>
          <Space>
            <Button type="primary" onClick={handleSearch}>搜索</Button>
            <Button onClick={handleReset}>重置</Button>
            <Button icon={<ReloadOutlined />} onClick={() => fetchUsers()} />
          </Space>
        </Col>
        <Col span={4}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            新增用户
          </Button>
        </Col>
      </Row>

      {/* 用户表格 */}
      <Table
        columns={columns}
        dataSource={users}
        rowKey="_id"
        loading={loading}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          onChange: (page, pageSize) => {
            setPagination(prev => ({ ...prev, current: page, pageSize: pageSize || 10 }));
          }
        }}
        scroll={{ x: 1200 }}
      />

      {/* 用户操作模态框 */}
      <Modal
        title={modalType === 'create' ? '新增用户' : '编辑用户'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 2, max: 20, message: '用户名长度在2-20个字符' }
            ]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          {modalType === 'create' && (
            <Form.Item
              label="密码"
              name="password"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, message: '密码长度不能少于6位' }
              ]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
          )}

          <Form.Item
            label="邮箱"
            name="email"
            rules={[
              { type: 'email', message: '请输入正确的邮箱格式' }
            ]}
          >
            <Input placeholder="请输入邮箱（可选）" />
          </Form.Item>

          <Form.Item
            label="手机号"
            name="tel"
            rules={[
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
            ]}
          >
            <Input placeholder="请输入手机号（可选）" />
          </Form.Item>

          <Form.Item
            label="用户角色"
            name="isAdmin"
            valuePropName="checked"
          >
            <Switch checkedChildren="管理员" unCheckedChildren="普通用户" />
          </Form.Item>

          {modalType === 'edit' && (
            <Form.Item
              label="用户状态"
              name="status"
              rules={[{ required: true, message: '请选择用户状态' }]}
            >
              <Select placeholder="请选择用户状态">
                <Option value="启用">启用</Option>
                <Option value="禁用">禁用</Option>
                <Option value="封禁">封禁</Option>
              </Select>
            </Form.Item>
          )}
        </Form>
      </Modal>
    </Card>
  );
}
